package itrans;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.sql.DataSource;
import java.sql.*;
import java.util.*;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.*;

public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("IT WORKS, but we don't take GET requests here :(");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		process(request, response);
	}
	
	public void process(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		String nextPage = request.getParameter("page");
		String authenticated = "true";
		int status = 0; // holds status of login
		
		HttpSession session = request.getSession(true);
		UserBean user = (UserBean) session.getAttribute(PublicConstants.USERBEAN_ATTR);
		
		if (!user.getLoggedIn()) {
			
			String username = request.getParameter(PublicConstants.USERNAME_PARAM);
            String password = request.getParameter(PublicConstants.PASSWORD_PARAM);
            
            // record the username and password values in a User Bean
			user.setUsername(username);
			user.setPassword(password);
			
			// in case malicious user posts these values
      	    user.setLoggedIn(false);
      	    user.setId(0);
      	    
			// attempt to login
      	    authenticate(user);
      	    if (user.getLoggedIn()) {
			}
			else {
				nextPage = "#login";
				authenticated = "false";
      	    }
		}
		
		session.setAttribute("page", nextPage);
		session.setAttribute("userId", user.getId());
		session.setAttribute("authenticated", authenticated);
		request.getRequestDispatcher("/WEB-INF/login_results.jsp").forward(request, response);
	}
	
	private void authenticate(UserBean user)
	{
		Connection con;
		String searchQuery = "SELECT * FROM Users WHERE USERNAME = ? AND PASSWORD = ?";
		try {
			DataSource dbcp = (DataSource)getServletContext().getAttribute("dbpool");
            con = dbcp.getConnection();

            PreparedStatement query = con.prepareStatement(searchQuery);
			query.setString(1, user.getUsername());
			query.setString(2, user.getPassword());
			ResultSet rs = query.executeQuery();
			
			// if a row is returned, they are authenticated
			if(rs.next()){ 
                // fill the userBean with the rest of the properties
                user.setId(rs.getInt("id"));
                user.setLoggedIn(true);
            }
            rs.close();
            query.close();
            con.close();
        }
        catch(SQLException ex) {
          System.err.println("SQLException: " + ex.getMessage());
        }
        catch (Exception e) {
          e.printStackTrace();
        }
	}
}
